import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { Popconfirm, Button, Table } from 'antd';
import styles from './RoleAuthUsers.less';
import UsersSelect from '../UserSelect';
import { columns1 } from './userConfig';

const RoleAuthUsers = (props, ref) => {
  const { title = '授权用户', userList, style } = props;
  // const dispatch = useDispatch();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [listOfSelectUser, setListOfSelectUser] = useState(userList || []);

  useImperativeHandle(ref, () => ({
    getListOfSelectUserIds: () => listOfSelectUser.map((d) => d.userId),
  }));

  useEffect(() => {
    if (userList?.length === 0) {
      return;
    }
    setListOfSelectUser(userList);
    return () => {};
  }, [userList]);

  const handOk = (selectUsers = []) => {
    setListOfSelectUser(selectUsers);
    setIsModalVisible(false);
  };

  const handleDel = (userId) => {
    setListOfSelectUser(listOfSelectUser.filter((d) => d.userId !== userId));
  };

  const onHandleCancel = () => {
    setListOfSelectUser([...listOfSelectUser]);
    setIsModalVisible(false);
  };

  const columnsAction = columns1.concat([
    {
      title: '操作',
      key: 'action',
      render: (record) => (
        <div>
          <Popconfirm title="确定要删除该用户吗？" onConfirm={() => handleDel(record.userId)}>
            <a>删除</a>
          </Popconfirm>
          {/* <Divider type="vertical" />
          <Button type="link" onClick={() => handleShowEdit('edit', record)}>取消授权</Button> */}
        </div>
      ),
    },
  ]);

  return (
    <>
      <div className={styles.root} style={{ ...style }}>
        <div className={styles.menuTitleWrapper}>
          <div className={styles.title}>{`${title}`}</div>
          <div>
            <Button type="link" onClick={() => setIsModalVisible(true)}>
              新增
            </Button>
          </div>
        </div>
        <div className={styles.menuTable}>
          <Table
            rowKey="userId"
            columns={columnsAction}
            dataSource={listOfSelectUser}
            pagination={{ pageSize: 5 }}
          />
        </div>
      </div>
      {isModalVisible && (
        <UsersSelect
          isModalVisible={isModalVisible}
          handOk={handOk}
          handleCancel={onHandleCancel}
          selectUsers={listOfSelectUser}
        />
      )}
    </>
  );
};

export default forwardRef(RoleAuthUsers);
